package com.ijiuchuang.jc_localization.model.tools;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Vibrator;

import com.ijiuchuang.jc_localization.R;
import com.ijiuchuang.jc_localization.bean.entity.BleDevice;
import com.ijiuchuang.jc_localization.bean.event.BeaconEvent;
import com.ijiuchuang.jc_localization.ble.BleUtil;
import com.ijiuchuang.jc_localization.ble.iBeaconClass;
import com.ijiuchuang.jc_localization.contract.tools.ToolsGuardsContract;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Veev on 2016/7/6
 *
 * @link 384506557@qq.com
 */
public class ToolsGuardsModel implements ToolsGuardsContract.Model {

    @Override
    public int getBleEnableRes() {
        return R.drawable.ic_bluetooth_searching_white_24dp;
    }

    private HashMap<String, BeaconEvent> beaconMap = new HashMap<>();
    /**
     * 扫描回调 - Bluetooth
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            // 数据处理
            BeaconEvent iBeacon = iBeaconClass.getBeacon(device, rssi, scanRecord);
            beaconMap.put(device.getAddress(), iBeacon);
        }
    };

    int count = 0;
    Subscription loop = null;

    @Override
    public void startScan(final Context context, final BleDevice bleDevice, final GuardsListener listener) {
        BleUtil.getBluetoothAdapter().startLeScan(mLeScanCallback);
        loop = Observable.interval(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        if (beaconMap.containsKey(bleDevice.getMac())) {
                            count = 0;
                            listener.isSafety(true);
                            listener.rssiUpdate(beaconMap.get(bleDevice.getMac()).rssi);
                            if (beaconMap.get(bleDevice.getMac()).isIbeacon) {
                                listener.heartRateUpdate(beaconMap.get(bleDevice.getMac()).heartRate);
                            } else {
                                listener.heartRateUpdate(0);
                            }
                            if (beaconMap.get(bleDevice.getMac()).isIbeacon) {
                                listener.powerUpdate(beaconMap.get(bleDevice.getMac()).power);
                            } else {
                                listener.powerUpdate(0);
                            }
                        } else {
                            listener.lostCount(count);
                            if (++count >= 5) {
                                voice(context);
                                vibration(context);
                                listener.isSafety(false);
                            }
                        }
                        beaconMap.clear();
                    }
                });
    }

    @Override
    public void stopScan(Context context) {
        BleUtil.getBluetoothAdapter().stopLeScan(mLeScanCallback);
        if (loop != null) {
            loop.unsubscribe();
        }
    }

    /**
     * 提示音
     * @param context
     */
    private void voice(Context context){
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(context, RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mp.prepare();
            mp.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 震动
     * @param context
     */
    private void vibration(Context context){
        /*
         * 想设置震动大小可以通过改变pattern来设定，如果开启时间太短，震动效果可能感觉不到
         * */
        Vibrator vibrator = (Vibrator)context.getSystemService(Service.VIBRATOR_SERVICE);
        long [] pattern = {100,100,100,100};   // 停止 开启 停止 开启
        vibrator.vibrate(pattern,-1);           //重复两次上面的pattern 如果只想震动一次，index设为-1
    }
}
